/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res = 0;
    int maxLength(TreeNode* root)
    {
        if(!root)
            return 0;
        return max(maxLength(root->left),maxLength(root->right))+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root)
            return 0;
        diameterOfBinaryTree(root->left);
        diameterOfBinaryTree(root->right);

        res = max(maxLength(root->left) + maxLength(root->right), res);

        return res;
    }
};


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res = 0;

    int dfs(TreeNode* root)
    {
        if(!root->left && !root->right)
            return 1;
        int left = root->left ? dfs(root->left) : 0;
        int right = root->right ? dfs(root->right) : 0;
        res = max(res, left+right);
        return max(left,right)+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root)
            return 0;

        dfs(root);

        return res;
    }
};